/*
 ********************************************************************************
 *
 * Copyright (c) 2019-2024 Renesas Electronics Corporation and/or its affiliates
 *
 ********************************************************************************
 */

package com.dialog.suotalib.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.dialog.suotalib.global.SuotaLibLog;

import androidx.annotation.NonNull;

/**
 * Helper Class for running things on main / UI thread
 */
public class MainThread {
    private static final String TAG = "MainThread";

    private static Handler handler;

    private static synchronized Handler getHandler() {
        if (handler == null) {
            handler = new Handler(Looper.getMainLooper());
        }
        return handler;
    }

    public static void runOnUiThread(@NonNull Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            if (SuotaLibLog.MAIN_THREAD)
                Log.d(TAG, "Already running on main thread");
            runnable.run();
            return;
        }

        if (SuotaLibLog.MAIN_THREAD)
            Log.d(TAG, "Move execution to main thread");
        getHandler().post(runnable);
    }

    public static void runOnUiThread(int delay, @NonNull Runnable runnable) {
        getHandler().postDelayed(runnable, delay);
    }
}
